package conf

import (
	"flag"
	"goqk/blockchain"
	"goqk/core/p2p"
	"goqk/core/tree"
	"os"
	"strconv"

	"github.com/joho/godotenv"
)

// NodeConfig type
type NodeConfig struct {
	Port                        int
	CAServerAddress             string
	CAPubKeyPath                string
	PrivateKeyPath              string
	PublicKeyPath               string
	CertPath                    string
	GossipBlockServerPort       int
	GossipTransactionServerPort int
	GossipBlockMembers          string
	GossipTransactionMembers    string
}

// Config type
var Config NodeConfig

// LoadNodeConfig - 读取节点配置
func LoadNodeConfig() (NodeConfig, error) {
	var config NodeConfig
	err := godotenv.Load("conf.env")
	if err != nil {
		return config, err
	}

	if size, err := strconv.Atoi(os.Getenv("Node.Port")); err == nil {
		config.Port = size
	} else {
		return config, err
	}
	config.CAPubKeyPath = os.Getenv("Node.CAPubKeyPath")
	config.CAServerAddress = os.Getenv("Node.CAServerAddress")
	config.PrivateKeyPath = os.Getenv("Node.PrivateKeyPath")
	config.PublicKeyPath = os.Getenv("Node.PublicKeyPath")
	config.CertPath = os.Getenv("Node.CertPath")
	if size, err := strconv.Atoi(os.Getenv("Node.GossipBlockServerPort")); err == nil {
		config.GossipBlockServerPort = size
	} else {
		return config, err
	}
	if size, err := strconv.Atoi(os.Getenv("Node.GossipTransactionServerPort")); err == nil {
		config.GossipTransactionServerPort = size
	} else {
		return config, err
	}
	config.GossipBlockMembers = os.Getenv("Node.GossipBlockMembers")
	config.GossipTransactionMembers = os.Getenv("Node.GossipTransactionMembers")
	return config, nil
}

// LoadLedgerConfig - 读取账本配置
func LoadLedgerConfig() (blockchain.BlockChainConfig, error) {
	var config blockchain.BlockChainConfig
	config.FileName = os.Getenv("Blockchain.FileName")
	if size, err := strconv.Atoi(os.Getenv("Blockchain.FileSize")); err == nil {
		config.FileSize = size
	} else {
		return config, err
	}
	if p, err := strconv.Atoi(os.Getenv("Blockchain.HTTPPort")); err == nil {
		config.HTTPPort = p
	} else {
		return config, err
	}

	return config, nil
}

// LoadP2PServerConfig - 读取服务器配置
func LoadP2PServerConfig() (p2p.P2PConfig, error) {
	var config p2p.P2PConfig
	if p, err := strconv.Atoi(os.Getenv("P2P.Port")); err == nil {
		config.Port = p
	} else {
		return config, err
	}
	config.Address = flag.String("addr",
		"localhost:"+strconv.Itoa(config.Port), "service address")

	return config, nil
}

// LoadTreeConfig - 读取bucket-tree的配置
func LoadTreeConfig() (tree.TreeConfig, error) {
	var config tree.TreeConfig
	if c, err := strconv.Atoi(os.Getenv("Tree.Capacity")); err == nil {
		config.Capacity = c
	} else {
		return config, err
	}
	if l, err := strconv.Atoi(os.Getenv("Tree.Level")); err == nil {
		config.Level = l
	} else {
		return config, err
	}

	return config, nil
}
